package org.sgmiller.quickstem.collections;

import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.sgmiller.quickstem.Transaction;

/**
 * Provides a transactional queue datastructure.
 * 
 * @author scott
 *
 * @param <E>
 */
public class TransactionalQueue<E> extends AbstractQueue<E> {

	TransactionalList<E> values=new TransactionalList<E>();
	
	@Override
	public Iterator<E> iterator() {
		return values.iterator();
	}

	@Override
	public int size() {
		return values.size();
	}

	@Override
	public boolean offer(E e) {
		return values.add(e);
	}

	@Override
	public E peek() {
		return values.get(0);
	}

	@Override
	public E poll() {
		try {
			return values.remove(0);
		} catch (ArrayIndexOutOfBoundsException ai) {
			throw new NoSuchElementException();
		}
	}
	
	@Override
	public void clear() {
		values.clear();
	}

	public static void main(String[] args) {
		TransactionalQueue<String> m=new TransactionalQueue<String>();
		Transaction.begin();
		m.offer("hi");		
		Transaction.commit();
		m.offer("there");		
		Transaction.begin();
		m.offer("Sparky");
		Transaction.rollback();
		while (!m.isEmpty()) {
			System.out.println(m.poll());
		}
		
	}
}
